package com.codestation.henloserver

import android.content.Context

import java.io.FileNotFoundException
import java.io.IOException

import fi.iki.elonen.NanoHTTPD
import java.io.InputStream

internal class AndroidWebServer(private val context: Context, port: Int) : NanoHTTPD(port) {

    override fun serve(session: NanoHTTPD.IHTTPSession): NanoHTTPD.Response {
        val response: NanoHTTPD.Response

        var uri = session.uri
        if (uri.equals("/")) {
            uri = "/index.html"
        }

        response = try {
            var mimeType: String = NanoHTTPD.getMimeTypeForFile(uri)
            val inputStream: InputStream = context.assets.open(uri.substring(1))
            NanoHTTPD.newChunkedResponse(NanoHTTPD.Response.Status.OK, mimeType, inputStream)
        } catch (e: FileNotFoundException) {
            NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.NOT_FOUND, "text/plain","Not found:$uri")
        } catch (e: IOException) {
            e.printStackTrace()
            NanoHTTPD.newFixedLengthResponse("<html><body><h3>Internal server error</h3></body></html>")
        }

        return response
    }

}
